# -- coding: utf-8 --
import requests
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import os
import time
import re


def get_url(url):
    headers = {
        'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36 Edg/84.0.522.59",
    }
    response = requests.get(url, headers=headers)
    return response


def get_song(song_name, song_id):
    url = baseurl.format(song_id)
    content = get_url(url).content
    print(f'正在下载{song_name}.mp3')
    with open(song_name+'.mp3', 'wb') as f:
        f.write(content)


if __name__ == '__main__':
    baseurl = 'http://music.163.com/song/media/outer/url?id={}'
    url = input('复制歌曲链接或歌单链接或歌手链接到此处，并按下Enter键：')
    try:
        os.mkdir('./音乐')
    except:
        pass
    os.chdir('./音乐')
    p = r"[\/\\\:\*\?\"\<\>\|]"
    option = Options()
    # 下面4行是开启无头模式代码
    option.add_argument('--headless')
    option.add_argument('--disable-gpu')
    option.add_argument("window-size=1024,768")
    option.add_argument("--no-sandbox")
    driver = webdriver.Chrome(options=option)
    if 'song?id=' in url:
        song_id = url.split('=')[-1]
        driver.get(url)
        driver.switch_to.frame('contentFrame')
        title = driver.find_element_by_class_name('f-ff2').text
        title = re.sub(p, ' ', title)
        artist = driver.find_element_by_xpath('//p[@class="des s-fc4"]/span/a').text
        artist = re.sub(p, '&', artist)
        song_name = title + '-' + artist
        get_song(song_name, song_id)
    if 'playlist?id=' in url:
        driver.get(url)
        driver.switch_to.frame('contentFrame')
        playlist = driver.find_element_by_xpath('//h2[@class="f-ff2 f-brk"]').text
        playlist = re.sub(p, ' ', playlist)
        songs = driver.find_elements_by_xpath('//tr[@*]')
        try:
            os.mkdir(playlist)
        except:
            pass
        os.chdir(playlist)
        for song in songs:
            song_id = song.find_element_by_xpath('.//a').get_attribute('href').split('=')[-1]
            title = song.find_element_by_xpath('.//b').text.replace('\n', '')
            artist = song.find_element_by_xpath('.//div[@class="text"]').get_attribute('title')
            title = re.sub(p, ' ', title)
            artist = re.sub(p, ' & ', artist)
            song_name = title + '-' + artist
            get_song(song_name, song_id)
            time.sleep(0.3)
    if 'artist?id' in url:
        driver.get(url)
        driver.switch_to.frame('contentFrame')
        artist = driver.find_element_by_id('artist-name').text
        try:
            os.mkdir(artist)
        except:
            pass
        os.chdir(artist)
        songs = driver.find_elements_by_xpath('//tr[@*]')
        for song in songs:
            song_id = song.find_element_by_xpath('.//a').get_attribute('href').split('=')[-1]
            title = song.find_element_by_xpath('.//b').get_attribute('title')
            title = re.sub(p, ' ', title)
            song_name = title + '-' + artist
            get_song(song_name, song_id)
            time.sleep(0.3)
    driver.quit()
    print('*' * 100)
    print('下载完成')
    print('*' * 100)
